import {Directive, ElementRef, Input, Renderer2, OnChanges, SimpleChanges, AfterViewInit} from '@angular/core';

@Directive({
  selector: 'th[fixedLeft],th[fixedRight],td[fixedLeft],td[fixedRight]'
})
export class TbFixedDirective implements OnChanges, AfterViewInit{
  @Input() fixedLeft: string | boolean | undefined = false
  @Input() fixedRight: string | boolean | undefined = false
  constructor(private el: ElementRef, private rd2: Renderer2) {}
  private setFixedClass(el: HTMLElement, nodeType: 'th' | 'td', pos: 'left' | 'right') {
    this.rd2.addClass(el, `ml-table-fixed-${nodeType === 'th' ? 'thead': 'tbody'}-${pos}`)
  }
  private setLeftPx(el: HTMLElement, pos: 'left' | 'right') {
    const tableContainerEl = document.querySelector('.ml-table-container') as HTMLElement
    const tableEl = document.querySelector('table.ml-table') as HTMLElement
    const offset = pos === 'left' ? el.offsetLeft : (tableEl.clientWidth - el.offsetLeft - el.clientWidth)
    this.rd2.setStyle(el, pos,  offset + 'px')
  }

  ngAfterViewInit() {

  }

  ngOnChanges(changes: SimpleChanges) {
    const getPos =  (isFixedLeft: boolean): 'left' | 'right' => isFixedLeft ? 'left' : 'right'
    const isFixedLeft = !!this.fixedLeft || this.fixedLeft === ''
    const isFixedRight = !!this.fixedRight || this.fixedRight === ''
    if (!isFixedLeft && !isFixedRight) return
    // 添加类 fixed
    let nativeEl = this.el.nativeElement
    const nodeType = nativeEl.nodeName.toLowerCase()
    this.setLeftPx(nativeEl, getPos(isFixedLeft))
    this.setFixedClass(nativeEl, nodeType, getPos(isFixedLeft))
  }

}
